package com.oracle.rentcar.controller;

import ch.qos.logback.core.util.FileUtil;
import com.github.pagehelper.PageInfo;
import com.oracle.rentcar.pojo.Customer;
import com.oracle.rentcar.service.CustomerService;
import com.oracle.rentcar.util.Constant;
import com.oracle.rentcar.util.MyResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;


    @RequestMapping("delete_customer")
    public String deleteCustomer(int id) {
        //删除会员
        customerService.delete(id);

        return "redirect:/customer/select_customer";
    }


    @RequestMapping("select_customer")
    public String selectCustomer(
            @RequestParam(name = "currentPageNum", required = false, defaultValue = "1") Integer currentPageNum,
            @RequestParam(name = "cusName", required = false, defaultValue = "") String cusName,
            @RequestParam(name = "phone", required = false, defaultValue = "") String phone,
            Model model) {

        PageInfo<Map<String, Object>> pager = customerService.findCustomerByPage(currentPageNum, cusName, phone);

        List<Map<String, Object>> customerList = pager.getList();


        model.addAttribute("pager", pager);
        model.addAttribute("customerList", customerList);
        model.addAttribute("cusName", cusName);
        model.addAttribute("phone", phone);

        // 转发到/templates/customer/emp_list.html
        return "customer/customer_list";
    }

    @ResponseBody
    @RequestMapping("batch_delete_customer")
    public Map<String, Object> batchDeleteCustomers(Integer[] cusids) {

        // System.out.println(cusids);

        int n = customerService.removeCustomers(cusids);

        Map<String, Object> result = new HashMap<>();
        if (n > 0) {
            result.put("success", true);
            result.put("msg", "ok");
        } else {
            result.put("success", false);
            result.put("msg", "error");
        }

        return result;

    }

    @ResponseBody
    @RequestMapping("customer_name_exists")
    public MyResponse customerNameExists(String customerName) {

        boolean flag = customerService.checkCustomerNameExist(customerName);

        MyResponse myResponse = new MyResponse();

        if (flag == true) {
            //可以使用会员名
            myResponse.success();
        } else {
            //不能使用会员名
            myResponse.failure();
        }

        return myResponse;
    }

    /**
     * 注册会员
     *
     * @param customer 会员信息
     * @param file     上传的文件
     * @return
     */
    @RequestMapping("reg_customer")
    public String regCustomer(Customer customer, @RequestParam("head_img") MultipartFile file)
            throws FileNotFoundException, IOException {

        // 1.classpath目录
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        System.out.println("classpath:" + path.getAbsolutePath());

        // 2.上传文件的路径
        File upload = new File(path.getAbsolutePath(), "static/res/images/upload");
        System.out.println("upload:" + upload.getAbsolutePath());

        // 3.如果上传文件路径不存在，创建路径
        if (!upload.exists()) {
            upload.mkdirs();    // 创建目录， mk dirs 创建多级目录
        }

        // 4.得到上传文件的名字
        String fileName = file.getOriginalFilename();
        System.out.println("上传文件名：" + fileName);

        // 5.得到上传文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        // 6.修改原有的文件名字
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("修改后的上传文件名：" + fileName);

        // 7.参数1是保存的文件路径，参数2是修改后的文件名字
        File dest = new File(upload.getAbsolutePath(), fileName);
        System.out.println("上传文件：" + dest.getAbsolutePath());


        // 8.上传的file文件保存到dest中
        file.transferTo(dest);


        // 9.设置押金，会员创建日期，会员图片
        customer.setYajin(0.0);
        customer.setCreateTime(new Date());
        // 将修改后的上传文件名保存到pic属性中
        customer.setPic(fileName);

        // 10.保存会员到数据库
        customerService.reg(customer);


        return "redirect:/customer/select_customer";

    }


    @RequestMapping("show_update_customer")
    public ModelAndView showUpdateCustomer(int id){
        Customer customer = customerService.getCustomerById(id);

        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("customer", customer);
        //转发页面， /templates/customer/update_customer.html显示
        modelAndView.setViewName("customer/update_customer");

        return modelAndView;
    }

    @RequestMapping("update_customer")
    public String updateCustomer(Customer customer, @RequestParam("head_img") MultipartFile file)
            throws FileNotFoundException, IOException {

        // 1.得到上传文件的名字
        String fileName = file.getOriginalFilename();
        System.out.println("上传文件名：" + fileName);

        if(fileName != null){
            // 2.classpath目录
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            System.out.println("classpath:" + path.getAbsolutePath());

            // 3.上传文件的路径
            File upload = new File(path.getAbsolutePath(), "static/res/images/upload");
            System.out.println("upload:" + upload.getAbsolutePath());

            // 4.如果上传文件路径不存在，创建路径
            if (!upload.exists()) {
                upload.mkdirs();    // 创建目录， mk dirs 创建多级目录
            }

            // 5.得到上传文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));

            // 6.修改原有的文件名字
            fileName = UUID.randomUUID() + suffixName;
            System.out.println("修改后的上传文件名：" + fileName);

            // 7.参数1是保存的文件路径，参数2是修改后的文件名字
            File dest = new File(upload.getAbsolutePath(), fileName);
            System.out.println("上传文件：" + dest.getAbsolutePath());


            // 8.上传的file文件保存到dest中
            file.transferTo(dest);

            //9.把新文件名设置到customer中
            customer.setPic(fileName);
        }

        customerService.updateCustomerById(customer);

        return "redirect:/customer/select_customer";
    }
}
